package pt.ipleiria.estg.dei.ei.es2.bio;

import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.preference.PreferenceManager;
import android.provider.Telephony;
import android.test.ActivityInstrumentationTestCase2;
import android.view.View;
import android.widget.TextView;

import com.robotium.solo.Solo;

/**
 * Created by Ricardo on 05/03/2015.
 */
public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {
    private Solo solo;

    public MainActivityTest(){
        super(MainActivity.class);

    }

    @Override
    public void setUp() throws Exception {
        solo = new Solo(getInstrumentation(),getActivity());
    }

    @Override
    public void tearDown() throws Exception {
        solo.finishOpenedActivities();
    }

    //2.Dado que estou na aplicação,
    // Quando pressiono o botão "I'm here"
    // E as informações do meu contacto estão preenchidas (pelo menos nome e email),
    //Então deve ser-me exibida uma mensagem de confirmação da activação desta funcionalidade.
    public void testConfirmationDialog() throws Exception {
        clickForCheckIn();

        assertTrue("-----Não foi encontrado o titulo da AlertDialog------",solo.searchText(getActivity().getString(R.string.confirmationTitle))) ;
    }

    private void clickForCheckIn() {
        solo.unlockScreen();
        solo.clickOnActionBarItem(R.id.action_checkin);
    }

    //3.Dado que estou na mensagem de confirmação da funcionalidade "I'm here",
    //Quando pressiono no botão "Sim" e tenho rede,
    //Então os meus dados devem ser submetidos e partilhados com os restantes participantes que activaram a funcionalidade "I'm here"
    // e o botão deve mudar para o estado activo.
    public void testCheckIn()throws Exception{
        clickForCheckIn();
        solo.clickOnButton(getActivity().getString(R.string.okBtn));
        solo.waitForActivity(ParticipantsListActivity.class,3000);
        solo.assertCurrentActivity("--------Não foi para a lista de participantes------",ParticipantsListActivity.class);

        //verifica se o icon mudou para o de grupo

        assertCorrectIconInItem(R.id.action_checkin, R.drawable.ic_action_group);


    }

    private void assertCorrectIconInItem(int menuItemId, int expectedIconId) {

        assertTrue("Não apareceu o MenuItem", solo.waitForView(menuItemId));
        TextView v = (TextView) solo.getCurrentActivity().findViewById(menuItemId);
        Bitmap expected = ((BitmapDrawable)getActivity().getDrawable(expectedIconId)).getBitmap();
        Bitmap actual = ((BitmapDrawable)v.getCompoundDrawables()[0]).getBitmap();

        assertTrue("The icon has not changed",actual.sameAs(expected));
    }


    public void setupContactPreferences (String name, String email){
        SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(getActivity()).edit();
        editor.putString(getActivity().getString(R.string.prefs_key_name), name);
        editor.putString(getActivity().getString(R.string.prefs_key_email), email);
        editor.commit();

    }

    public void testNothingInContact () throws Exception{
        setupContactPreferences("","");
        clickForCheckIn();
        assertTrue("FILL in contact details not found", solo.searchText(getActivity().getString(R.string.alertDialogNoDataTittle)));

    }

    public void testNameMissingInContact () throws Exception{
        setupContactPreferences("","some@gmail.com");
        clickForCheckIn();
        assertTrue("FILL in contact details not found", solo.searchText(getActivity().getString(R.string.alertDialogNoDataTittle)));

    }

    public void testEmailMissingInContact () throws Exception{
        setupContactPreferences("some name","");
        clickForCheckIn();
        assertTrue("FILL in contact details not found", solo.searchText(getActivity().getString(R.string.alertDialogNoDataTittle)));

    }

    public void testNoCheckIn() throws Exception {
        setupContactPreferences("Jorge", "sample@x.com");

        clickForCheckIn();

        solo.clickOnButton(getActivity().getString(R.string.cancelBtn));

        solo.assertCurrentActivity("Activity is new", MainActivity.class);

        assertCorrectIconInItem(R.id.action_checkin, R.drawable.ic_action_person);
    }

    public void testFillInContact() throws Exception{

        setupContactPreferences("","");

        clickForCheckIn();

        solo.clickOnButton(getActivity().getString(R.string.okBtn));

        assertTrue("Não mudou para a actividade de Settings", solo.waitForActivity(SettingsActivity.class));

        solo.clickOnText(getActivity().getString(R.string.prefs_title_name));
        assertTrue("Não apareceu a caixa de para introdução de text", solo.waitForDialogToOpen());
        solo.enterText(0, "Sample Name");
        solo.clickOnButton(1);
        assertTrue("Não fechou a caixa para introdução de text", solo.waitForDialogToClose());

        solo.clickOnText(getActivity().getString(R.string.prefs_title_email));
        assertTrue("Não apareceu a caixa de para introdução de text", solo.waitForDialogToOpen());
        solo.enterText(0, "Sample@email.com");
        solo.clickOnButton(1);
        assertTrue("Não fechou a caixa para introdução de text", solo.waitForDialogToClose());

        solo.goBack();

        assertTrue("Não voltou à MainActivity", solo.waitForActivity(MainActivity.class));
        assertTrue("Não apresentou o AlertDialog", solo.waitForDialogToOpen());
        assertTrue("Dialog que apareceu foi a errada", solo.searchText(solo.getString(R.string.confirmationTitle)));
    }

    public void testNoFillInContact() throws Exception{
        setupContactPreferences("","");

        clickForCheckIn();

        solo.clickOnButton(getActivity().getString(R.string.okBtn));

        assertTrue("Não mudou para a actividade de Settings", solo.waitForActivity(SettingsActivity.class));
        solo.goBack();
        assertTrue("Não voltou à actividade MainActivity", solo.waitForActivity(MainActivity.class));

        assertCorrectIconInItem(R.id.action_checkin, R.drawable.ic_action_person);
    }

    public void testAlwaysVisible() throws Exception{
        setupContactPreferences("Name", "sample@email.com");

        solo.setWiFiData(true);

        solo.assertCurrentActivity("Not in main activity", MainActivity.class);

        View menuItem = solo.getView(R.id.action_checkin);
        assertNotNull(menuItem);
        assertEquals(View.VISIBLE, menuItem.getVisibility());

        assertCorrectIconInItem(R.id.action_checkin, R.drawable.ic_action_person);

        clickForCheckIn();

        solo.clickOnButton(getActivity().getString(R.string.okBtn));

        solo.waitForActivity(ParticipantsListActivity.class, 3000);
        solo.assertCurrentActivity("Not in ParticipantsListActivity",ParticipantsListActivity.class);

        menuItem = solo.getView(R.id.action_checkin);
        assertNotNull(menuItem);
        assertEquals(View.VISIBLE, menuItem.getVisibility());

        assertCorrectIconInItem(R.id.action_checkin, R.drawable.ic_action_group);

        //desligar
        solo.clickOnActionBarItem(R.id.action_checkin);
        menuItem = solo.getView(R.id.action_checkin);
        assertNotNull(menuItem);
        assertEquals(View.VISIBLE, menuItem.getVisibility());

        assertCorrectIconInItem(R.id.action_checkin,R.drawable.ic_action_person);
    }

    public void testCheckout() throws Exception{
        setupContactPreferences("Name", "sample@email.com");
        solo.setWiFiData(true);

        clickForCheckIn();

        solo.clickOnButton(getActivity().getString(R.string.okBtn));

        solo.waitForActivity(ParticipantsListActivity.class, 3000);

        assertCorrectIconInItem(R.id.action_checkin, R.drawable.ic_action_group);

        //desligar

        solo.clickOnActionBarItem(R.id.action_checkin);

        solo.sleep(3000);

        assertCorrectIconInItem(R.id.action_checkin,R.drawable.ic_action_person);
    }

    public void testNoNetwork() throws Exception{
        setupContactPreferences("Name", "sample@email.com");
        solo.setWiFiData(false);
        solo.setMobileData(false);

        clickForCheckIn();

        solo.clickOnButton(getActivity().getString(R.string.okBtn));

        assertTrue("No Network Dialog Found",solo.searchText(getActivity().getString(R.string.alertDialogNoNetworkMessage))) ;
    }
}
